import { _decorator, Component, BoxCollider, ITriggerEvent, Node } from 'cc';
import { BulletPropType, CollisionType } from '../framework/Enum';
const { ccclass, property } = _decorator;

@ccclass('SelfPlane')
export class SelfPlane extends Component {
    start() {
        this._explodeEffect = this.node.getChildByName("explode")
        this._blood = this.node.getChildByName("blood")
        this._bloodFace = this._blood.getChildByName("faceBox")
    }
    // 玩家飞机最大血量
    public lifeValue = 5
    // 玩家飞机当前血量
    private _currLife = 0
    // 当前是否死亡
    public isDie = false
    // 爆炸特效
    private _explodeEffect: Node = null
    // 整个血条节点
    private _blood: Node = null
    // 血条方块
    private _bloodFace: Node = null

    onEnable() {
        // 获取到当前的碰撞组件
        const collider = this.getComponent(BoxCollider)
        // 监听碰撞事件
        collider.on('onTriggerEnter', this._onTriggerEnter, this)
    }

    onDisEnable() {
        // 获取到当前的碰撞组件
        const collider = this.getComponent(BoxCollider)
        // 取消监听碰撞事件
        collider.off('onTriggerEnter', this._onTriggerEnter, this)
    }

    update(deltaTime: number) {

    }

    // 恢复血量
    public initLife() {
        this._currLife = this.lifeValue
        this.isDie = false
        this._explodeEffect.active = false
        this._bloodFace.setScale(2, 1, 1)
    }

    // 碰撞事件
    private _onTriggerEnter(e: ITriggerEvent) {
        // 获取碰撞物分组
        const collisionGroup = e.otherCollider.getGroup()
        if (collisionGroup === CollisionType.ENEMY) {
            // 敌方飞机扣除两滴血
            this._currLife -= 2
        } else if (collisionGroup === CollisionType.ENEMY_BULLET) {
            // 敌方子弹扣除一滴血
            this._currLife--
        } else {
            // 道具
            return
        }
        this._bloodFace.setScale(2 * this._currLife / this.lifeValue, 1, 1)
        this._blood.active = true

        // 如果血量低于0，进入濒死状态
        if (this._currLife <= 0) {
            this.isDie = true
            this._explodeEffect.active = true
        }
    }
}

